package com.micro.edu.filter;

import com.micro.edu.rpc.IMicroUserRpc;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class AuthorityFilter implements GlobalFilter, Ordered {

    @Reference
    private IMicroUserRpc microUserRpc;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        if (path.contains("/user/") || path.contains("/code/")) {
            return chain.filter(exchange);
        }
        HttpCookie cookie = request.getCookies().getFirst("token");
        if (cookie == null) {
            return errorResponse(exchange);
        }
        if (StringUtils.isBlank(cookie.getName())) {
            return errorResponse(exchange);
        }
        String token = cookie.getValue();
        String userInfo = microUserRpc.info(token);
        if (StringUtils.isBlank(userInfo)) {
            return errorResponse(exchange);
        }
        return chain.filter(exchange);
    }

    private Mono<Void> errorResponse(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        DataBuffer wrap = response.bufferFactory().wrap("未授权".getBytes());
        return response.writeWith(Mono.just(wrap));
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
